package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.model.vo.CourseBaseInfoVo;
import com.xuecheng.content.model.vo.TeachplanVo;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CourseTeacherService;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private CourseTeacherService courseTeacherService;

    /**
     * 课程分类查询
     * @param companyId 机构id
     * @param pageParams 分页查询参数
     * @param queryCourseParamsDto 查询条件
     * @return 查询结果
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {

        // 拼装查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        // 根据名称模拟查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()), CourseBase::getName, queryCourseParamsDto.getCourseName());
        // 根据课程审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus());
        // 根据发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDto.getPublishStatus());
        // 根据培训机构id拼装查询条件
        queryWrapper.eq(CourseBase::getCompanyId, companyId);

        // 创建page分页参数对象，参数：当前页码，每页记录数
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 开始进行分页查询
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        // 数据列表
        List<CourseBase> items = pageResult.getRecords();
        // 总记录数
        long total = pageResult.getTotal();

        PageResult<CourseBase> courseBasePageResult = new PageResult<>(items, total, pageParams.getPageNo(), pageParams.getPageSize());

        return courseBasePageResult;
    }

    /**
     * 新增课程
     * @param companyId 机构id
     * @param addCourseDto 课程信息
     * @return 课程详细信息
     */
    @Override
    @Transactional
    public CourseBaseInfoVo createCourseBase(Long companyId, AddCourseDto addCourseDto) {

        /*// 参数的合法性效验
        if (StringUtils.isBlank(addCourseDto.getName())) {
            // throw new RuntimeException("课程名称为空");
            XueChengPlusException.cast("课程名称为空");
        }

        if (StringUtils.isBlank(addCourseDto.getMt())) {
            // throw new RuntimeException("课程分类为空");
            XueChengPlusException.cast("课程分类为空");
        }

        if (StringUtils.isBlank(addCourseDto.getSt())) {
            // throw new RuntimeException("课程分类为空");
            XueChengPlusException.cast("课程分类为空");
        }

        if (StringUtils.isBlank(addCourseDto.getGrade())) {
            // throw new RuntimeException("课程等级为空");
            XueChengPlusException.cast("课程等级为空");
        }

        if (StringUtils.isBlank(addCourseDto.getTeachmode())) {
            // throw new RuntimeException("教育模式为空");
            XueChengPlusException.cast("教育模式为空");
        }

        if (StringUtils.isBlank(addCourseDto.getUsers())) {
            // throw new RuntimeException("适应人群为空");
            XueChengPlusException.cast("适应人群为空");
        }

        if (StringUtils.isBlank(addCourseDto.getCharge())) {
            // throw new RuntimeException("收费规则为空");
            XueChengPlusException.cast("收费规则为空");
        }*/

        // 向课程基本信息表course_base写入数据
        CourseBase courseBase = new CourseBase();
        // 将传入的页面参数放到courseBase对象
        BeanUtils.copyProperties(addCourseDto, courseBase); // 只要属性名称一致就可以拷贝
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        // 审核参数默认为未提交
        courseBase.setAuditStatus("202002");
        // 发布状态为未发布
        courseBase.setStatus("203001");
        // 插入数据库
        int insert = courseBaseMapper.insert(courseBase);
        if(insert <= 0) {
            throw new RuntimeException("添加课程失败");
        }

        // 向课程营销表course_market写入数据
        CourseMarket courseMarket = new CourseMarket();
        // 将页面输入的数据拷贝到courseMarket
        BeanUtils.copyProperties(addCourseDto, courseMarket);
        // 课程的id
        Long courseId = courseBase.getId();
        courseMarket.setId(courseId);
        // 保存营销信息
        saveCourseMarket(courseMarket);
        // 从数据库查询课程的详细信息，包括两部分
        CourseBaseInfoVo courseBaseInfo = getCourseBaseInfo(courseId);

        return courseBaseInfo;
    }

    // 查询课程信息
    public CourseBaseInfoVo getCourseBaseInfo(Long courseId) {

        // 从课程基本信息表查询
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null) {
            return null;
        }

        // 从课程营销表查询
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);

        // 组装在一起
        CourseBaseInfoVo courseBaseInfoVo = new CourseBaseInfoVo();
        BeanUtils.copyProperties(courseBase, courseBaseInfoVo);
        if(courseMarket != null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoVo);
        }

        // 通过courseCategoryMapper查询分类信息，将分类名称放在courseBaseInfoVo对象
        // 课程分类的名称设置到courseBaseInfoVo
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoVo.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoVo.setMtName(courseCategoryByMt.getName());

        return courseBaseInfoVo;
    }

    /**
     * 修改课程
     * @param companyId 机构id
     * @param editCourseDto 修改课程信息
     * @return 课程详细信息
     */
    @Override
    @Transactional
    public CourseBaseInfoVo updateCourseBase(Long companyId, EditCourseDto editCourseDto) {

        // 拿到课程id
        Long courseId = editCourseDto.getId();
        // 查询课程信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null) {
            XueChengPlusException.cast("课程不存在");
        }

        // 数据合法性效验
        // 根据具体的业务逻辑去效验
        // 本机构只能修改本机构的课程
        if(!companyId.equals(courseBase.getCompanyId())) {
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }

        // 封装数据
        BeanUtils.copyProperties(editCourseDto, courseBase);
        // 修改时间
        courseBase.setChangeDate(LocalDateTime.now());

        // 更新数据库
        int i = courseBaseMapper.updateById(courseBase);
        if(i <= 0) {
            XueChengPlusException.cast("修改课程失败");
        }

        // 更新营销信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto, courseMarket);
        saveCourseMarket(courseMarket);

        // 查询课程信息
        CourseBaseInfoVo courseBaseInfo = getCourseBaseInfo(courseId);

        return courseBaseInfo;
    }

    /**
     * 删除课程
     * @param id
     * @param companyId
     */
    @Override
    @Transactional
    public void deleteCourseBase(Long id, Long companyId) {
        // 获取课程
        CourseBase courseBase = courseBaseMapper.selectById(id);
        Long courseBaseCompanyId = courseBase.getCompanyId();

        // 本机构才可以删除本机构的课程
        if(!companyId.equals(courseBaseCompanyId)) {
            XueChengPlusException.cast("不能删除非本机构的课程");
        }

        // 课程的审核状态为未提交时方可删除
        if(!courseBase.getAuditStatus().equals("202002")) {
            XueChengPlusException.cast("课程的审核状态为已提交，删除失败");
        }

        // 删除课程需要删除课程相关的基本信息，营销信息，课程计划和课程教师信息
        // 删除课程基本信息
        courseBaseMapper.deleteById(id);
        // 删除课程营销信息
        courseMarketMapper.deleteById(id);
        // 删除课程计划
        List<TeachplanVo> teachplanTree = teachplanService.findTeachplanTree(id);
        for (TeachplanVo teachplanVo : teachplanTree) {
            for (TeachplanVo teachPlanTreeNode : teachplanVo.getTeachPlanTreeNodes()) {
                teachplanService.deleteTeachplan(teachPlanTreeNode.getId());
            }
            teachplanService.deleteTeachplan(teachplanVo.getId());
        }
        // 删除课程教师信息
        List<CourseTeacher> courseTeachers = courseTeacherService.selectTeacherList(id);
        List<Long> teacherIds = courseTeachers.stream()
                .map(CourseTeacher::getId)
                .collect(Collectors.toList());
        courseTeacherService.deleteBatchIds(teacherIds);
    }

    // 单独写一个方法保存营销信息，逻辑：存在则更新，不存在则添加
    public int saveCourseMarket(CourseMarket courseMarket) {

        // 参数的合法性效验
        String charge = courseMarket.getCharge();
        if(StringUtils.isEmpty(charge)) {
            // throw new RuntimeException("收费规则为空");
            XueChengPlusException.cast("收费规则为空");
        }
        // 如果课程收费，价格没有填写也需要抛出异常
        if(charge.equals("201001")) {
            if(courseMarket.getOriginalPrice() == null || courseMarket.getOriginalPrice().floatValue() <= 0) {
                // throw new RuntimeException("课程的价格不能为空并且大于0");
                XueChengPlusException.cast("课程的价格不能为空并且大于0");
            }
            if(courseMarket.getPrice() == null || courseMarket.getPrice().floatValue() <= 0) {
                // throw new RuntimeException("课程的价格不能为空并且大于0");
                XueChengPlusException.cast("课程的价格不能为空并且大于0");
            }
        }

        // 从数据库查询营销信息，存在则更新，不存在则添加
        Long id = courseMarket.getId(); // 主键
        CourseMarket courseMarket1 = courseMarketMapper.selectById(id);
        if(courseMarket1 == null) {
            // 插入数据库
            int insert = courseMarketMapper.insert(courseMarket);
            return insert;
        } else {
            // 将courseMarket拷贝到selectById
            BeanUtils.copyProperties(courseMarket, courseMarket1);
            courseMarket1.setId(courseMarket.getId());
            // 更新
            int i = courseMarketMapper.updateById(courseMarket);
            return i;
        }
    }
}
